﻿using Microsoft.Extensions.Configuration;
using Surpass.Model.Dto.RequestParamsDto;
using Surpass.Model.Dto.ResponseDto.ResponseModel.ResultModel;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dapper;
using Surpass.Model.SysDomain;

namespace Surpass.DapperRepository.Repository
{
    public class RoleRepository
    {
        private readonly IConfiguration _configuration;
        public RoleRepository(IConfiguration configuration)
        {
            _configuration = configuration;
        }
        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="sysRoleRelationParams"></param>
        /// <returns></returns>
        public ResponseModel<bool> AddUserRole(SysRoleRelationParams sysRoleRelationParams)
        {
            var result = new  ResponseModel<bool>();
            using (var conn = new SqlConnection(_configuration.GetConnectionString("MsSqlServer")))
            {
                conn.Open();  //打开连接
                using (var begin = conn.BeginTransaction())
                {
                    try
                    {
                        var count = 0;
                        foreach (var item in sysRoleRelationParams.RoleIds.Split(','))
                        {
                            //SqlParameter[] sqls =
                            //{
                            //    new SqlParameter("@UserId",sysRoleRelationParams.UserId)
                            //};
                            count+=conn.Execute($"insert into Sys_User_Role_Relation(UserId,RoleId) values('{sysRoleRelationParams.UserId}','{item}')", null, begin);
                        }
                        if (count>0)
                        {
                            begin.Commit();
                            return result.Succeed(true);
                        }
                        else
                        {
                            begin.Rollback();
                        }
                        
                    }
                    catch (Exception ex)
                    {
                        begin.Rollback();
                        throw ex;
                    }
                }
            }
            return result.Fail("添加失败");
        }


        /// <summary>
        /// 根据用户ID获取所有角色ID
        /// </summary>
        /// <param name="userid"></param>
        /// <returns></returns>
        public PageResponse<SysUserRoleRelation> GetUserId(long userid)
        {
            var result = new PageResponse<SysUserRoleRelation>();
            using (var conn =new SqlConnection(_configuration.GetConnectionString("MsSqlServer")))
            {
                var sql = $"select * from Sys_User_Role_Relation where UserId='{userid}'";
                result.PageData =  conn.Query<SysUserRoleRelation>(sql).ToList();
            }
            return result;
        }
    }
}
